package io.vertx.kue.util

import io.vertx.kue.queue.JobState
import io.vertx.core.Vertx
import io.vertx.core.json.JsonObject
import io.vertx.redis.RedisClient
import io.vertx.redis.RedisOptions

/**
 * Helper class for operating Redis.
 *
 * @author Eric Zhao
 */
object RedisHelper {

  private val VERTX_KUE_REDIS_PREFIX = "vertx_kue"

  /**
   * Factory method for creating a Redis client in Vert.x context.
   *
   * @param vertx  Vertx instance
   * @param config configuration
   * @return the new Redis client instance
   */
  fun client(vertx: Vertx, config: JsonObject): RedisClient {
    return RedisClient.create(vertx, options(config))
  }

  /**
   * Factory method for creating a default local Redis client configuration.
   *
   * @param config configuration from Vert.x context
   * @return the new configuration instance
   */
  fun options(config: JsonObject): RedisOptions {
    return RedisOptions()
            .setHost(config.getString("redis.host", "127.0.0.1"))
            .setPort(config.getInteger("redis.port", 6379)!!)
  }

  /**
   * Wrap the key with prefix of Vert.x Kue namespace.
   *
   * @param key the key to wrap
   * @return the wrapped key
   */
  fun getKey(key: String): String {
    return VERTX_KUE_REDIS_PREFIX + ":" + key
  }

  /**
   * Generate the key of a certain task state with prefix of Vert.x Kue namespace.
   *
   * @param state task state
   * @return the generated key
   */
  fun getStateKey(state: JobState): String {
    return VERTX_KUE_REDIS_PREFIX + ":jobs:" + state.name
  }

  /**
   * Create an id for the zset to preserve FIFO order.
   *
   * @param id id
   */
  fun createFIFO(id: Long): String {
    var idLen = "" + ("" + id).length
    var len = 2 - idLen.length
    while (len-- > 0)
      idLen = "0" + idLen
    return idLen + "|" + id
  }

  /**
   * Parse out original ID from zid.
   *
   * @param zid zid
   */
  fun stripFIFO(zid: String): String {
    return zid.substring(zid.indexOf('|') + 1)
  }

  /**
   * Parse out original ID from zid.
   *
   * @param zid zid
   */
  fun numStripFIFO(zid: String): Long {
    return java.lang.Long.parseLong(zid.substring(zid.indexOf('|') + 1))
  }
}
